<template>
  <div class="face-recognition-container">
    <el-card shadow="never" class="main-card">
      <el-tabs type="card" class="custom-tabs">
        <!-- 人脸搜索标签页 -->
        <el-tab-pane label="人脸检测">
          <div class="search-pane">
            <el-form ref="elForm1" :model="formData1" :rules="rules" size="medium" label-width="100px" class="search-form">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="人脸图片" prop="face">
                    <div class="upload-container">
                      <div>
                      </div>
                      <el-upload
                        class="face-upload"
                        list-type="picture-card"
                        action="#"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :before-remove="beforeRemove"
                        
                        :auto-upload="false"
                        :show-file-list="false"
                        name="files"
                       
                        :on-change="handleSearchFaceChange"
                       accept="image/*,.jpg,.jpeg,.png,.gif,.bmp,.webp"
                      >
                      <img v-if="formData1.face" class="img" :src="formData1.face.url" alt="" srcset="">
                         <i v-else  class="el-icon-plus img"></i>
                        <div slot="tip" class="el-upload__tip">上传人脸图片</div>
                      </el-upload>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
             
                <el-col :span="24" class="search-btn-col">
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="searchForm"
                      size="medium"
                      class="search-btn"
                    >
                      开始检测
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            
            <el-divider></el-divider>
            
            <div class="result-section">
              <h3 class="result-title">检测结果</h3>
              <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%"
                class="result-table"
                v-loading="loading"
                empty-text="暂无数据"
              >
               <el-table-column type="index" label="№" />
              <el-table-column label="人脸坐标" align="center">
                  <template slot-scope="scope">
                      <div class="coordinate-detail">
                        <div v-for="(value, key) in scope.row.bounding_box" :key="key">
                          {{ key }}: {{ value }}
                        </div>
                      </div>
                  </template>
              </el-table-column>
                <!-- <el-table-column prop="faceId" label="人脸ID" width="180" align="center"></el-table-column>
                <el-table-column prop="imgId" label="图片ID" width="240" align="center"></el-table-column>
                <el-table-column prop="similarity" label="相似度" width="120" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="getSimilarityTagType(scope.row.similarity)">
                      {{ scope.row.similarity }}
                    </el-tag>
                  </template>
                </el-table-column> -->
                <!-- <el-table-column prop="faceCoordinate" label="人脸坐标" align="center">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                      <div class="coordinate-detail">
                        <p v-for="(value, key) in scope.row.bounding_box" :key="key">
                          {{ key }}: {{ value }}
                        </p>
                      </div>
                      <div slot="reference" class="coordinate-wrapper">
                        <i class="el-icon-location-information"></i> 查看坐标
                      </div>
                    </el-popover>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 人脸对比标签页 -->
        <el-tab-pane label="人脸对比">
          <div class="compare-pane">
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" class="compare-form">
              <div class="upload-group">
                <div class="upload-item">
                  <h4 class="upload-title">上传第一张人脸图片</h4>
                  <el-form-item prop="faceImg1">
                    <el-upload
                      class="compare-upload"
                      list-type="picture-card"
                      action="#"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      :limit="1"
                      :auto-upload="false"
                      :show-file-list="true"
                      name="files"
                      :disabled="isShowFace1"
                      :on-change="handleChange"
                      :on-exceed="handleExceed"
                    >
                      <i class="el-icon-plus"></i>
                      <div slot="tip" class="el-upload__tip">支持jpg/png格式</div>
                    </el-upload>
                  </el-form-item>
                </div>
                
                <div class="upload-item">
                  <h4 class="upload-title">上传第二张人脸图片</h4>
                  <el-form-item prop="faceImg2">
                    <el-upload
                      class="compare-upload"
                      list-type="picture-card"
                      action="#"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      :limit="1"
                      :auto-upload="false"
                      name="files"
                      :show-file-list="true"
                      :disabled="isShowFace2"
                      :on-change="handleChangeFaceImg2"
                    
                    >
                      <i class="el-icon-plus"></i>
                      <div slot="tip" class="el-upload__tip">支持jpg/png格式</div>
                    </el-upload>
                  </el-form-item>
                </div>
              </div>
              
              <div class="compare-btn-container">
                <el-button
                  type="primary"
                  icon="el-icon-refresh-left"
                  @click="resetCompareForm"
                  size="medium"
                  class="compare-btn"
                >
                  重置
                </el-button>
                <el-button
                  type="success"
                  icon="el-icon-search"
                  @click="submitForm"
                  size="medium"
                  class="compare-btn"
                  :loading="comparing"
                >
                  开始对比
                </el-button>
              </div>
            </el-form>
            
            <div class="compare-result" v-if="showResult">
              <el-divider><i class="el-icon-s-data"></i> 对比结果</el-divider>
              
              <el-row :gutter="20" class="result-grid">
                <el-col :span="12">
                  <el-card shadow="hover" class="result-card">
                    <div slot="header" class="result-card-header">
                      <span>人脸1信息</span>
                    </div>
                    <div class="result-card-content">
                      <div class="result-item">
                        <span class="result-label">位置信息：</span>
                        <span class="result-value">{{ resp.image1_face }}</span>
                      </div>
                    </div>
                  </el-card>
                </el-col>
                
                <el-col :span="12">
                  <el-card shadow="hover" class="result-card">
                    <div slot="header" class="result-card-header">
                      <span>人脸2信息</span>
                    </div>
                    <div class="result-card-content">
                      <div class="result-item">
                        <span class="result-label">位置信息：</span>
                        <span class="result-value">{{ resp.image2_face }}</span>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              
              <el-row>
                <el-col :span="24">
                  <el-card shadow="hover" class="similarity-card">
                    <div class="similarity-content">
                      <div class="similarity-text">相似度</div>
                      <div class="similarity-value">{{ resp.similarity }}</div>
                      <el-progress 
                        :percentage="similarityPercentage" 
                        :color="customColors"
                        :stroke-width="16"
                        class="similarity-progress"
                      ></el-progress>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="人脸搜索">
          <div class="search-pane">
            <el-form ref="elForm2" :model="formDataSearch" :rules="rules" size="medium" label-width="100px" class="search-form">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="人脸图片" prop="face">
                    <div class="upload-container">
                      <div>
                        
                      </div>
                      <el-upload
                        class="face-upload"
                        list-type="picture-card"
                        action="#"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :before-remove="beforeRemove"
                        
                        :auto-upload="false"
                        :show-file-list="false"
                        name="files"
                       
                        :on-change="handleSearchFaceChangeSearch"
                       accept="image/*,.jpg,.jpeg,.png,.gif,.bmp,.webp"
                      >
                      <img v-if="formDataSearch.face" class="img" :src="formDataSearch.face.url" alt="" srcset="">
                         <i v-else  class="el-icon-plus img"></i>
                        <div slot="tip" class="el-upload__tip">上传人脸图片</div>
                      </el-upload>
                    </div>
                  </el-form-item>
                </el-col>
              <el-col :span="6">
                  <el-form-item label="人脸库" prop="faceSetName">
                    <el-input
                      v-model="formDataSearch.faceSetName"
                      placeholder="请输入人脸库"
                      clearable
                      class="custom-input"
                    >
                      <template slot="prepend">
                        <i class="el-icon-collection"></i>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                
             





              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="24" class="search-btn-col">
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="searchFormSubimt"
                      size="medium"
                      class="search-btn"
                    >
                      开始搜索
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            
            <el-divider></el-divider>
            
            <div class="result-section">
              <h3 class="result-title">搜索结果</h3>
              <el-table
                :data="formDataSearchData"
                border
                stripe
                style="width: 100%"
                class="result-table"
                v-loading="loading"
                empty-text="暂无数据"
              >
<!-- bounding_box
: 
{width: 270, top_left_y: 385, top_left_x: 366, height: 338}
external_image_id
: 
"tW6mqCtJ"
face_id
: 
"p19jklns"
similarity
: 
1 -->


                <el-table-column prop="face_id" label="人脸ID" width="180" align="center"></el-table-column>
                <el-table-column prop="external_image_id" label="图片ID" width="240" align="center"></el-table-column>
                <el-table-column prop="similarity" label="相似度" width="120" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="getSimilarityTagType(scope.row.similarity)">
                      {{ scope.row.similarity }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="faceCoordinate" label="人脸坐标" align="center">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                      <div class="coordinate-detail">
                        <p v-for="(value, key) in scope.row.bounding_box" :key="key">
                          {{ key }}: {{ value }}
                        </p>
                      </div>
                      <div slot="reference" class="coordinate-wrapper">
                        <i class="el-icon-location-information"></i> 查看坐标
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { detectFace,searchFace,compare } from "@/api/system/database";
import Vue from "vue";

export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      comparing: false,
      showResult: false,
      tableData: [],
    
      mockData: {
        faceId: "10096",
        imgId: "522258b2aeca41aabf695fd91cfd4850",
        similarity: "0.9866348342",
        faceCoordinate: JSON.stringify({
          width: 91, 
          top_left_y: 42, 
          top_left_x: 48, 
          height: 115
        }),
      },
      formData1: {
        face: "",
        faceCollection: undefined,
        faceId: undefined,
        similarity: undefined,
        No: 10,
      },

      formDataSearch: {
        face: "",
       faceSetName:'',
      },

      formDataSearchData: [], //sousuo
      rules: {
        faceSetName: [
          { required: true, message: "请输入人脸集", trigger: "blur" }
        ],
      },
      isShowFace1: false,
      isShowFace2: false,
      isShowFace3: false,
      formData: {
        files: [],
      },
      resp: {
        similarity: "",
        image1_face: "",
        image2_face: "",
      },
      customColors: [
        { color: '#f56c6c', percentage: 20 },
        { color: '#e6a23c', percentage: 40 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 80 },
        { color: '#6f7ad3', percentage: 100 }
      ]
    };
  },
  computed: {
    similarityPercentage() {
      if (!this.resp.similarity) return 0;
      const num = parseFloat(this.resp.similarity.replace('%', ''));
      return Math.round(num);
    }
  },
  methods: {
    getSimilarityTagType(similarity) {
      const value = parseFloat(similarity);
      if (value >= 0.9) return 'success';
      if (value >= 0.7) return 'warning';
      return 'danger';
    },
    
    handleChange(file, fileList) {
      if (fileList.length >= 1) {
        this.isShowFace1 = true;
      }
      this.formData.files.push(file.raw);
      
      this.showResult = false;
    },
    
    handleChangeFaceImg2(file, fileList) {
      if (fileList.length >= 1) {
        this.isShowFace2 = true;
      }
      this.formData.files.push(file.raw);
      this.showResult = false;
    },
    
    handleSearchFaceChange(file, fileList) {
      if (fileList.length >= 1) {
        this.isShowFace3 = true;
      }
      console.log(file);
      
      this.formData1.face = file;

    },
    handleSearchFaceChangeSearch(file, fileList){
      if (fileList.length >= 1) {
        this.isShowFace3 = true;
      }
      this.formDataSearch.face = file;
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.isShowFace1 = false;
        this.isShowFace2 = false;
        this.isShowFace3 = false;
      }
      this.formData.files = this.formData.files.filter(f => f.name !== file.name);
    },
    
    handlePreview(file) {
      console.log(file);
    },
    
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${fileList.length} 个文件`);
    },
    
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
    },
    
    resetCompareForm() {
      this.formData.files = [];
      this.isShowFace1 = false;
      this.isShowFace2 = false;
      this.showResult = false;
      this.$refs.elForm.resetFields();
    },
    
    submitForm() {
      if (this.formData.files.length < 2) {
        this.$message.error("请上传两张人脸图片进行对比");
        return;
      }
       let form = new FormData();
      for (const item of this.formData.files) {
        form.append("files", item);
      }
      
     compare(form).then((response) => {
  // Format the response data
  const similarity = Number(response.data.similarity * 100).toFixed(2) + "%";
  
  Vue.set(this.resp, "similarity", similarity);
  Vue.set(this.resp, "image1_face", JSON.stringify(response.data.image1_face.bounding_box, null, 2));
  Vue.set(this.resp, "image2_face", JSON.stringify(response.data.image2_face.bounding_box, null, 2));
  this.comparing = false;
}).catch((error) => {
  console.error("Comparison failed:", error);
  this.comparing = false;
})
     this.showResult = true;
    },
    
    searchForm() {
      if (!this.formData1.face) {
        this.$message.error("请上传人脸图片");
        return;
      }
      
        detectFace({file:this.formData1.face.raw}).then(response => {
          console.log(response);
            this.$message.success(response.msg);
          this.tableData = response.data.faces;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
        
      this.$refs.elForm1.validate(valid => {
        if (!valid) return;
        
        this.loading = true;
      });
    },
    searchFormSubimt(){
       if (!this.formDataSearch.face) {
        this.$message.error("请上传人脸图片");
        return;
      }
       this.$refs.elForm2.validate(valid => {
        if (!valid) return;
        const a = {
          file:this.formDataSearch.face.raw,
          faceSetName:this.formDataSearch.faceSetName
        }
        
    searchFace(a).then((res)=>{
     this.formDataSearchData = res.data.faces
    })
       })
    }
  }
};
</script>

<style lang="scss" scoped>
.face-recognition-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
  
  .main-card {
    border-radius: 8px;
    border: none;
    
    ::v-deep .el-card__body {
      padding: 0;
    }
  }
  
  .custom-tabs {
    ::v-deep .el-tabs__header {
      margin: 0;
      background-color: #fff;
      border-radius: 8px 8px 0 0;
    }
    
    ::v-deep .el-tabs__item {
      height: 50px;
      line-height: 50px;
      font-size: 16px;
      padding: 0 25px;
      
      &.is-active {
        color: #409EFF;
        font-weight: bold;
      }
    }
  }
  
  .search-pane {
    padding: 20px;
    
    .search-form {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      .upload-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 200px;
      }
      
      ::v-deep .custom-input {
        .el-input-group__prepend {
          background-color: #f5f7fa;
          border-right: none;
        }
        
        .el-input__inner {
          border-left: none;
        }
      }
      
      .custom-input-number {
        width: 100%;
        
        ::v-deep .el-input-number__decrease,
        ::v-deep .el-input-number__increase {
          background: #f5f7fa;
        }
      }
      
      .search-btn-col {
        display: flex;
        justify-content: flex-end;
      }
      
      .search-btn {
        width: 150px;
        height: 40px;
        font-size: 16px;
      }
    }
    
    .result-section {
      margin-top: 20px;
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      .result-title {
        color: #606266;
        margin-bottom: 20px;
        font-size: 18px;
        display: flex;
        align-items: center;
        
        &:before {
          content: "";
          display: inline-block;
          width: 4px;
          height: 18px;
          background-color: #409EFF;
          margin-right: 10px;
          border-radius: 2px;
        }
      }
      
      ::v-deep .result-table {
        th {
          background-color: #f8fafc;
          color: #606266;
          font-weight: bold;
        }
      }
      
      .coordinate-detail {
        // p {
        //   margin: 5px 0;
        //   color: #606266;
        // }
      }
      
      .coordinate-wrapper {
        cursor: pointer;
        color: #409EFF;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
  
  .compare-pane {
    padding: 20px;
    
    .compare-form {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      .upload-group {
        display: flex;
        justify-content: space-around;
        margin-bottom: 20px;
        
        .upload-item {
          width: 45%;
          
          .upload-title {
            color: #606266;
            margin-bottom: 15px;
            text-align: center;
          }
          
          .compare-upload {
            display: flex;
            flex-direction: column;
            align-items: center;
            
            ::v-deep .el-upload--picture-card {
              width: 200px;
              height: 200px;
              line-height: 200px;
              margin-bottom: 10px;
            }
            
            ::v-deep .el-upload-list__item {
              width: 200px;
              height: 200px;
            }
            
            .el-upload__tip {
              color: #909399;
              font-size: 12px;
              text-align: center;
            }
          }
        }
      }
      
      .compare-btn-container {
        display: flex;
        justify-content: center;
        margin-top: 30px;
        
        .compare-btn {
          width: 150px;
          height: 40px;
          font-size: 16px;
          margin: 0 15px;
        }
      }
    }
    
    .compare-result {
      margin-top: 30px;
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      ::v-deep .el-divider__text {
        background-color: #fff;
        color: #409EFF;
        font-size: 16px;
      }
      
      .result-grid {
        margin-bottom: 20px;
        
        .result-card {
          border-radius: 8px;
          
          .result-card-header {
            font-weight: bold;
            color: #409EFF;
            border-bottom: 1px solid #ebeef5;
            padding: 12px 20px;
          }
          
          .result-card-content {
            padding: 15px;
            
            .result-item {
              margin-bottom: 10px;
              
              .result-label {
                color: #909399;
                font-weight: bold;
              }
              
              .result-value {
                color: #606266;
              }
            }
          }
        }
      }
      
      .similarity-card {
        border-radius: 8px;
        border: none;
        background-color: #f8fafc;
        
        .similarity-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 20px;
          
          .similarity-text {
            font-size: 16px;
            color: #909399;
            margin-bottom: 10px;
          }
          
          .similarity-value {
            font-size: 36px;
            font-weight: bold;
            color: #409EFF;
            margin-bottom: 20px;
          }
          
          .similarity-progress {
            width: 80%;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  
  ::v-deep .hide .el-upload--picture-card {
    display: none;
  }
}
.img{
  width: 150px;
  height: 150px;
}
</style>